package com.region.spring.cloud.core.event;

import com.region.loadbalancer.group.GroupServer;
import com.region.loadbalancer.group.Server;
import com.region.loadbalancer.monitor.event.Event;
import com.region.loadbalancer.monitor.event.EventState;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liujieyu
 * @date 2024/10/22 11:09
 * @desciption
 */
public class SpringCloudEvent implements Event {

    private String instanceId;

    private GroupServer groupServer;

    private DiscoveryClient discoveryClient;

    public SpringCloudEvent(String instanceId, GroupServer groupServer, DiscoveryClient discoveryClient) {
        this.instanceId = instanceId;
        this.groupServer = groupServer;
        this.discoveryClient = discoveryClient;
    }

    @Override
    public EventState state() {
        return EventState.SCHEDULE_CYCLE;
    }

    @Override
    public void event(GroupServer groupServer) {
        List<ServiceInstance> instances = discoveryClient.getInstances(instanceId);
        if (instances != null && !instances.isEmpty()) {
            List<Server> servers = new ArrayList<>();
            for (ServiceInstance instance : instances) {
                servers.add(Server.builder()
                        .host(instance.getHost())
                        .port(instance.getPort())
                        .protocol(instance.getScheme())
                        .build());
            }
            groupServer.getManager().updateServer(servers);
        }
    }

    @Override
    public void run() {
        this.event(this.groupServer);
    }
}
